const router = require('express').Router()
const { User, Article, Writing, Agree_log, sequelize, Op } = require('../config/sql')
const { wrap } = require('../tool')
const fs = require('fs/promises')
const { join } = require('path')

// 获取登录页文章
router.get('/writing', wrap(async (req, res) => {
   const [{ title, agree, main, id }] = await Writing.findAll({
      attributes: ['title', 'main', 'agree', 'id'],
      limit: 1,
      order: [
         ['id', 'DESC']
      ]
   })
   res.send({
      code: 200,
      title,
      agree,
      main,
      id
   })
}))

// 登录页文章点赞
router.get('/writing/agree', wrap(async (req, res) => {
   const { id } = req.query
   if (!id) throw '316'
   await Writing.update({
      agree: sequelize.literal('agree+1')
   }, {
      where: {
         id
      },
   })
   res.send({
      code: 200
   })
}))

// 阅读文章
router.get('/read', wrap(async (req, res) => {
   const { user, query: { id } } = req
   if (!id) throw '316'
   const [article] = await Article.findAll({
      attributes: ['id', 'uid', 'title', 'main', 'read', 'pushdateAt', 'abstract', 'tag', 'type', 'so', 'classif'],
      where: {
         id,
         state: 1
      }
   })
   if (!article) throw '404'
   console.log(user);
   if (article.so == 1 && (!user || article.uid != user.account)) res.send({
      code: 325,
      msg: '无效访问'
   })
   const { uid } = article
   const [_user] = await User.findAll({
      where: {
         uid
      }
   })
   const original = await Article.findAll({
      attributes: ['id'],
      where: {
         uid,
         state: 1,
         so: 0,
         type: 0
      }
   })
   article.increment('read')
   const send = {
      code: 200,
      article,
      nickname: _user.nickname,
      profile: _user.profile,
      original: original.length,
      agree: await article.agree,
   }
   if (user) {
      const agree_log = await Agree_log.findAll({
         where: {
            uid: user.account,
            aid: article.id
         }
      })
      send.isAgree = Boolean(agree_log.length)
   }
   res.send(send)
}))

// 编辑页路由
router.get('/editor', wrap(async (req, res) => {
   let { id } = req.query
   let html = await fs.readFile(join(__dirname, '../../public/view/markdown.html'))
   html = html.toString()
   if (!id) return res.send(html)
   id = +id
   if (isNaN(id)) return res.send(html)
   res.send(html.replace('data-id=""', `data-id="${id}"`))
}))

// 文章详情页路由
router.get('/article/:id', wrap(async (req, res) => {
   let { id } = req.params
   id = +id
   if (isNaN(id)) return res.send({ code: 404 })
   let html = await fs.readFile(join(__dirname, '../../public/view/Details_page.html'))
   html = html.toString()
   res.send(html.replace('data-id=""', `data-id="${id}"`))
}))

// 推荐文章
router.get('/recomendar', wrap(async (req, res) => {
   const { user, query: { page } } = req
   if (isNaN(Number(page))) throw '316'
   const articleSql = await Article.findAll({
      attributes: ['id', 'title', 'read', 'uid', 'cover_type', 'cover', 'abstract'],
      where: {
         state: 1,
         so: 0,
         delete: 0,
         cover_type: { [Op.ne]: 0 }
      },
      order: [
         ['read', 'DESC'],
      ],
      limit: 10,
      offset: page * 10
   })
   const article = []
   for (const iterator of articleSql) {
      const info = {
         agree: await iterator.agree,
         collection: await iterator.collection,
         nickname: await iterator.nickname,
      }
      if (user) {
         const agree_log = await Agree_log.findAll({
            where: {
               uid: user.account,
               aid: iterator.id
            }
         })
         info.isAgree = Boolean(agree_log.length)
      }
      article.push(Object.assign(info, iterator.dataValues))
   }
   res.send({
      code: 200,
      article
   })
}))

module.exports = router